package com.sinba.common.user.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.sinba.common.system.dao.ITransactionRecordDAO;
import com.sinba.common.system.dto.SingleGroupReportStatDTO;
import com.sinba.common.system.dto.TransactionRecordDTO;
import com.sinba.common.system.entity.TransactionRecord;
import com.sinba.common.system.service.ITransactionRecordService;
import com.sinba.common.user.dao.IAccountDAO;
import com.sinba.common.user.dao.IRegisterUserDAO;
import com.sinba.common.user.dto.AccountDTO;
import com.sinba.common.user.entity.Account;
import com.sinba.common.user.entity.RegisterUser;
import com.sinba.common.utils.DoubleFormat;
import com.sinba.common.utils.InvestmentSum;
import com.sinba.common.utils.TranType;

public class AccountService implements IAccountService {
	@Autowired
	private IRegisterUserDAO registerUserDAO;
	@Autowired
	private IAccountDAO accountDAO;
	@Autowired
	private ITransactionRecordDAO transactionRecordDAO;
	@Autowired
	private ITransactionRecordService transactionRecordService;
	private Integer total = 0;
	//冲值/转账
	@Transactional
	public String deltaTransfer(String loginName,String transAccount,Double value,String dtype){
		if(loginName.equals(transAccount)){//判断转出与转入账号是否一样
			return "转账失败，转出、转入账号相同，请检查!";//转出、转入账号相同
		}else if(StringUtils.hasText(loginName) && value!=null){
			//不允许转给未激活会员
			RegisterUser regUser = registerUserDAO.findUniqueBy("loginName",transAccount);
			if(regUser!=null && regUser.getActivationTime()==null){
				return "不允许转给未激活的会员!";
			}
			
			//转出会员
			RegisterUser zhuanChuUser = registerUserDAO.findUniqueBy("loginName",loginName);
			
			//判断是否上线转下线
//			if(!regUser.getLinkcode().startsWith(zhuanChuUser.getLinkcode())){
//				return "Only to the lower transfer, transfer not to superiors!<br>只能向下级转账,不能向上级转账!";
//			}
			
			Double balance = transactionRecordService.findUserBalance(loginName, dtype);
			if(balance>=value){//判断转出的账号余额是否足够
				//转入账号相加
				if(regUser!=null){
					//转出交易记录
					TransactionRecord tr = new TransactionRecord();
					tr.setLoginName(loginName);
					tr.setTransactionObject(transAccount);
					tr.setTransactionType(TranType.ZhuanZhang);
					transactionRecordService.updateTran(tr, dtype, DoubleFormat.format(value), "CUT");
					
					//转入交易记录
					TransactionRecord tr1 = new TransactionRecord();
					tr1.setLoginName(transAccount);
					tr1.setTransactionObject(loginName);
					tr1.setTransactionType(TranType.ZhuanZhang);
					transactionRecordService.updateTran(tr1, dtype, DoubleFormat.format(value), "ADD");
					return "恭喜您,转账成功!";
					
					
//					//判断是不是同一个团队
//					RegisterUser loginNameUser = registerUserDAO.findUniqueBy("loginName",loginName);
//					RegisterUserQueryDTO qdto = new RegisterUserQueryDTO();
//					qdto.setLinkCode(loginNameUser.getLinkcode());
//					qdto.setLoginName(transAccount);
//					qdto.setLimit(1);
//					PageDTO pagedto = registerUserDAO.myTeamPager(qdto, null, null);
//					if(pagedto.getTotalSize()>0){
//						
//					}else{
//						return "不在同一团队不允许转账，请检查!";
//					}
					
				}else{
					return "转账失败，转入的账号不存在，请检查!";
				}
				
			}else{
				return "转账失败，余额不足，请检查!";//余额不足
			}
		}else{
			return "转账失败，信息不正确，请检查!";
		}
	}
	@Transactional
	public void recharge(String loginName,Double sum){
		RegisterUser user = registerUserDAO.findUniqueBy("loginName",loginName);
		Account ac = user.getAccount();
		ac.setBalance(DoubleFormat.format(ac.getBalance()+sum));
		accountDAO.merge(ac);
		
		transactionRecordDAO.save(new TransactionRecord(loginName, 
				"system", "财务充值", 
				DoubleFormat.format(sum), 
				new Date(), 
				"财务充值"));

		
	}
	
	@Transactional
	private void leaderManagementAward(Double liangJiang,String loginName){
//		System.out.println("领导人管理奖"+loginName+">>"+liangJiang);
//		2.领导人管理奖：获取销售佣金1-5代佣金提成（得到直推下面会员的销售佣金5%，根据会员级别）
		//
//					等级        佣金代数     获取比例
		//
//					1级            -            -
//					2级            1            5%
//					3级            2            5%
//					4级            3            5%
//					5级            4            5%
//					6级            5            5%
		if(StringUtils.hasLength(loginName)){
			RegisterUser user = registerUserDAO.findUniqueBy("loginName",loginName);
			if(user!=null && user.getRecommendUser()!=null){
				RegisterUser user1 = null;
				RegisterUser user2 = null;
				RegisterUser user3 = null;
				RegisterUser user4 = null;
				RegisterUser user5 = null;
				RegisterUser user6 = null;
				//获取一代
				user1 = registerUserDAO.findUniqueBy("loginName",user.getRecommendUser());
				if(user1!=null && "VIP1,VIP2,VIP3,VIP4,VIP5,皇冠会员".indexOf(user1.getRegisterLevel())!=-1){
//					Account ac = user1.getAccount();
//					ac.setBalance(ac.getBalance()+Double.parseDouble(df.format(liangJiang*0.05)));
//					accountDAO.merge(ac);
//					transactionRecordDAO.save(new TransactionRecord(user1.getLoginName(), 
//							loginName, "销售管理佣金", 
//							Double.parseDouble(df.format(liangJiang*0.05)), 
//							new Date(), 
//							"销售管理佣金:激活会员编号为:"+loginName+"("+user.getRegisterLevel()+"),销售管理佣金:"+Double.parseDouble(df.format(liangJiang*0.05))));

//					System.out.println("领导人管理奖:会员编号为:"+loginName+"会员进行"+user.getRegisterLevel()+"激活，作为领导人将得到1代佣金提成:"+liangJiang*0.05);
				}
				
				//获取二代
				if(user1!=null && user1.getRecommendUser()!=null){
					user2 = registerUserDAO.findUniqueBy("loginName",user1.getRecommendUser());
					if(user2!=null && "VIP2,VIP3,VIP4,VIP5,皇冠会员".indexOf(user2.getRegisterLevel())!=-1){
						Account ac = user2.getAccount();
						//余额+销售佣金的5%
						ac.setBalance(DoubleFormat.format(ac.getBalance()+liangJiang*0.05));
						
						accountDAO.merge(ac);
						transactionRecordDAO.save(new TransactionRecord(user2.getLoginName(), 
								loginName, "销售管理佣金", 
								DoubleFormat.format(liangJiang*0.05), 
								new Date(), 
								"销售管理佣金:激活会员编号为:"+loginName+"("+user.getRegisterLevel()+")，销售管理佣金:"+DoubleFormat.format(liangJiang*0.05)));

//						System.out.println("领导人管理奖:会员编号为:"+loginName+"会员进行"+user.getRegisterLevel()+"激活，作为领导人将得到2代佣金提成:"+liangJiang*0.05);
					}
				}
				
				//获取三代
				if(user2!=null && user2.getRecommendUser()!=null){
					user3 = registerUserDAO.findUniqueBy("loginName",user2.getRecommendUser());
					if(user3!=null && "VIP3,VIP4,VIP5,皇冠会员".indexOf(user3.getRegisterLevel())!=-1){
						Account ac = user3.getAccount();
						//余额+销售佣金的5%
						ac.setBalance(DoubleFormat.format(ac.getBalance()+liangJiang*0.05));
						accountDAO.merge(ac);
						transactionRecordDAO.save(new TransactionRecord(user3.getLoginName(), 
								loginName, "销售管理佣金", 
								DoubleFormat.format(ac.getBalance()+liangJiang*0.05), 
								new Date(), 
								"销售管理佣金:激活会员编号为:"+loginName+"("+user.getRegisterLevel()+"),销售管理佣金:"+DoubleFormat.format(liangJiang*0.05)));

//						System.out.println("领导人管理奖:会员编号为:"+loginName+"会员进行"+user.getRegisterLevel()+"激活，作为领导人将得到3代佣金提成:"+liangJiang*0.05);
					}
				}

				//获取四代
				if(user3!=null && user3.getRecommendUser()!=null){
					user4 = registerUserDAO.findUniqueBy("loginName",user3.getRecommendUser());
					if(user4!=null && "VIP4,VIP5,皇冠会员".indexOf(user4.getRegisterLevel())!=-1){
						Account ac = user4.getAccount();
						//余额+销售佣金的5%
						ac.setBalance(DoubleFormat.format(ac.getBalance()+liangJiang*0.05));
						accountDAO.merge(ac);
						transactionRecordDAO.save(new TransactionRecord(user4.getLoginName(), 
								loginName, "销售管理佣金", 
								DoubleFormat.format(ac.getBalance()+liangJiang*0.05), 
								new Date(), 
								"销售管理佣金:激活会员编号为:"+loginName+"("+user.getRegisterLevel()+")，销售管理佣金:"+DoubleFormat.format(liangJiang*0.05)));

//						System.out.println("领导人管理奖:会员编号为:"+loginName+"会员进行"+user.getRegisterLevel()+"激活，作为领导人将得到4代佣金提成:"+liangJiang*0.05);
					}
				}
		
				//获取五代
				if(user4!=null && user4.getRecommendUser()!=null){
					user5 = registerUserDAO.findUniqueBy("loginName",user4.getRecommendUser());
					if(user5!=null && "VIP5,皇冠会员".indexOf(user5.getRegisterLevel())!=-1){
						Account ac = user5.getAccount();
						ac.setBalance(DoubleFormat.format(ac.getBalance()+liangJiang*0.05));
						accountDAO.merge(ac);
						transactionRecordDAO.save(new TransactionRecord(user5.getLoginName(), 
								loginName, "销售管理佣金", 
								DoubleFormat.format(ac.getBalance()+liangJiang*0.05), 
								new Date(), 
								"销售管理佣金:激活会员编号为:"+loginName+"("+user.getRegisterLevel()+")，销售管理佣金:"+DoubleFormat.format(liangJiang*0.05)));

//						System.out.println("领导人管理奖:会员编号为:"+loginName+"会员进行"+user.getRegisterLevel()+"激活，作为领导人将得到5代佣金提成:"+liangJiang*0.05);
					}
				}
				//获取六代
				if(user5!=null && user5.getRecommendUser()!=null){
					user6 = registerUserDAO.findUniqueBy("loginName",user5.getRecommendUser());
					if(user6!=null && "皇冠会员".indexOf(user6.getRegisterLevel())!=-1){
						Account ac = user6.getAccount();
						ac.setBalance(DoubleFormat.format(ac.getBalance()+liangJiang*0.05));
						accountDAO.merge(ac);
						transactionRecordDAO.save(new TransactionRecord(user6.getLoginName(), 
								loginName, "销售管理佣金", 
								DoubleFormat.format(ac.getBalance()+liangJiang*0.05), 
								new Date(), 
								"销售管理佣金:激活会员编号为:"+loginName+"("+user.getRegisterLevel()+"),销售管理佣金:"+DoubleFormat.format(liangJiang*0.05)));

//						System.out.println("领导人管理奖:会员编号为:"+loginName+"会员进行"+user.getRegisterLevel()+"激活，作为领导人将得到5代佣金提成:"+liangJiang*0.05);
					}
				}
			}
			
		}
					
	}
//	5.财富见点佣金：会员均可享受财富区内， A B两组无限层见点30%的奖金。（日封顶为本人投资金额的10倍）。(每天12点发放)
//		6.见点管理佣金：获得下5代所有财富见点佣金佣金提成(每天12点发放)
//		         佣金代数     获取比例
	//
//		         -            -
//		            1            20%
//		            2            10%
//		            3             5%
//		            4             5%
//		            5             3%
	@Transactional
	public void lookPointAward(String loginName){
		
		//要激活的会员 
		RegisterUser activeUser = registerUserDAO.findUniqueBy("loginName", loginName);
		//判断是否是AB区
		if(activeUser!=null 
				&& activeUser.getContactNo()!=null 
				&& ("aArea".equals(activeUser.getRegisterLocation()) || "bArea".equals(activeUser.getRegisterLocation()))){
			
			String registerLevel = activeUser.getRegisterLevel();
			Double dynamicAssign =	0D;
			if("体验会员".equals(registerLevel))
				dynamicAssign = 60D;
			if("VIP1".equals(registerLevel))
				dynamicAssign = 120D;
			if("VIP2".equals(registerLevel))
				dynamicAssign = 240D;
			if("VIP3".equals(registerLevel))
				dynamicAssign = 480D;
			if("VIP4".equals(registerLevel))
				dynamicAssign = 960D;
			if("VIP5".equals(registerLevel))
				dynamicAssign = 1920D;
			if("皇冠会员".equals(registerLevel))
				dynamicAssign = 3840D;
			//得到当前要激活会员的 接点人
			RegisterUser contactUser = registerUserDAO.findUniqueBy("loginName", activeUser.getContactNo());
			//判断我的接点人是不是C区,如果是C区，那么接点人的接点人可以拿到财富见点佣金
			if(contactUser!=null && contactUser.getContactNo()!=null && "cArea".equals(contactUser.getRegisterLocation())){
				System.out.println("财富见点佣金.......");
				//得到能拿财富见点佣金的会员
				RegisterUser lookPointAwardUser = registerUserDAO.findUniqueBy("loginName", contactUser.getContactNo());

				transactionRecordDAO.save(new TransactionRecord(lookPointAwardUser.getLoginName(), 
						loginName, "财富见点佣金", 
						DoubleFormat.format(dynamicAssign*0.3),
						new Date(), 
						"财富见点佣金:激活会员编号为:"+loginName+"("+activeUser.getRegisterLevel()+"),财富见点佣金:"+DoubleFormat.format(dynamicAssign*0.3)));
				
				//倒钩奖
				daoGuaAward(loginName,DoubleFormat.format(dynamicAssign*0.3),"财富见点佣金",lookPointAwardUser.getActivationTime());
				
				//财富见点佣金拿完后，开始平衡转换	
				abcChange(loginName);
				
				//见点管理佣金
				lookPointManagementAward(DoubleFormat.format(dynamicAssign*0.3),lookPointAwardUser.getLoginName());
			}
		}
	}
	/**
	 * 统计我下面的所有会员
	 * @param loginName
	 */
	@Transactional
	private void getABCAreaUserTotal(String loginName){
		//得到我下面的ABC区会员
		List<RegisterUser> abcUser = registerUserDAO.findBy("contactNo", loginName);
		total++;
		for(RegisterUser ru : abcUser){
			getABCAreaUserTotal(ru.getLoginName());
		}
	}
	
	/**
	 * ABC区相互转换
	 * @param loginName
	 */
	@Transactional
	private void abcChange(String loginName){
		System.out.println("财富见点佣金拿完后，开始平衡转换");
		//要激活的会员 
		RegisterUser activeUser = registerUserDAO.findUniqueBy("loginName", loginName);
		if(activeUser!=null && activeUser.getContactNo()!=null){
			//得到接点人的会员
			RegisterUser contactUser = registerUserDAO.findUniqueBy("loginName", activeUser.getContactNo());
			
			if(contactUser!=null && contactUser.getContactNo()!=null){
				//得到我同一层的会员
				List<RegisterUser> lists = registerUserDAO.findBy("contactNo", contactUser.getContactNo());
				Map<String,Integer> maps = new HashMap<String, Integer>();
				for(RegisterUser entity : lists){
					total = 0;
					getABCAreaUserTotal(entity.getLoginName());
					maps.put(entity.getLoginName(), total);
				}
				boolean result = true;
				Integer temp = 0;
				//判断是否是一样的值
				for(String key : maps.keySet()){
					System.out.println(key+"::::"+maps.get(key));
					if(temp!=0 && maps.get(key)!=temp){
						result = false;
						break;
					}
					temp = maps.get(key);
							
				}
				System.out.println("判断是否是一样的:"+result);
				if(true){
					System.out.println("进行排序::::::");
					//对MAP进行排序
					//排序前的输出
			        Set set = maps.entrySet();
			        Iterator i = set.iterator();
			        while(i.hasNext()){
			            Map.Entry<String, Integer> entry1=(Map.Entry<String, Integer>)i.next();
			        }
			        //排序后的输出
			        List<Map.Entry<String, Integer>> info = new ArrayList<Map.Entry<String, Integer>>(maps.entrySet());
			        Collections.sort(info, new Comparator<Map.Entry<String, Integer>>() {
			            public int compare(Map.Entry<String, Integer> obj1, Map.Entry<String, Integer> obj2) {
			                return obj2.getValue() - obj1.getValue();
			            }
			        });
			        //判断是否相等
			        for (int j = 0; j<info.size();j++) {
			        	if(j==0){
			        		RegisterUser reguser = registerUserDAO.findUniqueBy("loginName", info.get(j).getKey());
			        		reguser.setRegisterLocation("aArea");
			        		registerUserDAO.merge(reguser);
			        	}
			        	if(j==1){
			        		RegisterUser reguser = registerUserDAO.findUniqueBy("loginName", info.get(j).getKey());
			        		reguser.setRegisterLocation("bArea");
			        		registerUserDAO.merge(reguser);
			        	}
			        	if(j==2){
			        		RegisterUser reguser = registerUserDAO.findUniqueBy("loginName", info.get(j).getKey());
			        		reguser.setRegisterLocation("cArea");
			        		registerUserDAO.merge(reguser);
			        	}
			        	if(j>2){
			        		RegisterUser reguser = registerUserDAO.findUniqueBy("loginName", info.get(j).getKey());
			        		reguser.setContactNo(null);
			        		reguser.setRemark("这里出错了，怎么这层有多于三个会员的?");
			        		registerUserDAO.merge(reguser);
			        	}
			        }
		        }
				
				abcChange(contactUser.getContactNo());
			}
			
			
			
		}
	}
	
	
	@Transactional
	private void lookPointManagementAward(Double lookPointAward,String loginName){
//		6.见点管理佣金：获得下5代所有财富见点佣金佣金提成(每天12点发放)
//        佣金代数     获取比例
//
//        -            -
//		2级            1            20%
//		3级            2            10%
//		4级            3             5%
//		5级            4             5%
//		6级            5             3%
		Map<String, Double>  map = new HashMap<String, Double>();
		map.put("VIP1", 0.1d);
		map.put("VIP2", 0.1d);
		map.put("VIP3", 0.05d);
		map.put("VIP4", 0.05d);
		map.put("VIP5", 0.05d);
		map.put("皇冠会员", 0.05d);
		if(StringUtils.hasLength(loginName)){
			RegisterUser user = registerUserDAO.findUniqueBy("loginName",loginName);
			if(loginName!=null){
				RegisterUser user1 = null;
				RegisterUser user2 = null;
				RegisterUser user3 = null;
				RegisterUser user4 = null;
				RegisterUser user5 = null;
				RegisterUser user6 = null;
				//获取一代
				user1 = registerUserDAO.findUniqueBy("loginName",loginName);
				if(user1!=null && "VIP1,VIP2,VIP3,VIP4,VIP5,皇冠会员".indexOf(user1.getRegisterLevel())!=-1){
//					Account ac = user1.getAccount();
//					ac.setBalance(ac.getBalance()+lookPointAward*map.get(user1.getRegisterLevel()));
//					accountDAO.merge(ac);
//					transactionRecordDAO.save(new TransactionRecord(user1.getLoginName(), 
//							loginName, "财富见点管理佣金", 
//							lookPointAward*map.get(user1.getRegisterLevel()), 
//							new Date(), 
//							"财富见点管理佣金:激活会员编号为:"+loginName+"("+user.getRegisterLevel()+")，获得财富见点管理佣金:"+lookPointAward*map.get(user1.getRegisterLevel())));
//
//					
//					System.out.println("见点管理佣金:会员编号为:"+loginName+"会员进行"+user.getRegisterLevel()+"激活，作为领导人("+user1.getRegisterLevel()+")将得到1代相应财富见点佣金佣金提成:"+lookPointAward*map.get(user1.getRegisterLevel()));
				}
				
				//获取二代
				if(user1!=null && user1.getRecommendUser()!=null){
					user2 = registerUserDAO.findUniqueBy("loginName",user1.getRecommendUser());
					if(user2!=null && "VIP2,VIP3,VIP4,VIP5,皇冠会员".indexOf(user2.getRegisterLevel())!=-1){
						Account ac = user2.getAccount();
						ac.setBalance(DoubleFormat.format(ac.getBalance()+lookPointAward*map.get(user2.getRegisterLevel())));
						accountDAO.merge(ac);
						transactionRecordDAO.save(new TransactionRecord(user2.getLoginName(), 
								loginName, "财富见点管理佣金", 
								lookPointAward*map.get(user2.getRegisterLevel()), 
								new Date(), 
								"财富见点管理佣金:激活会员编号为:"+loginName+"("+user.getRegisterLevel()+"),获得财富见点管理佣金:"+lookPointAward*map.get(user2.getRegisterLevel())));

//						System.out.println("见点管理佣金:会员编号为:"+loginName+"会员进行"+user.getRegisterLevel()+"激活，作为领导人("+user2.getRegisterLevel()+")将得到2代相应财富见点佣金佣金提成:"+lookPointAward*map.get(user2.getRegisterLevel()));
					}
				}
				
				//获取三代
				if(user2!=null && user2.getRecommendUser()!=null){
					user3 = registerUserDAO.findUniqueBy("loginName",user2.getRecommendUser());
					if(user3!=null && "VIP3,VIP4,VIP5,皇冠会员".indexOf(user3.getRegisterLevel())!=-1){
						Account ac = user3.getAccount();
						ac.setBalance(DoubleFormat.format(ac.getBalance()+lookPointAward*map.get(user3.getRegisterLevel())));
						accountDAO.merge(ac);
						transactionRecordDAO.save(new TransactionRecord(user3.getLoginName(), 
								loginName, "财富见点管理佣金", 
								lookPointAward*map.get(user3.getRegisterLevel()), 
								new Date(), 
								"财富见点管理佣金:激活会员编号为:"+loginName+"("+user.getRegisterLevel()+"),获得财富见点管理佣金:"+lookPointAward*map.get(user3.getRegisterLevel())));

//						System.out.println("见点管理佣金:会员编号为:"+loginName+"会员进行"+user.getRegisterLevel()+"激活，作为领导人("+user3.getRegisterLevel()+")将得到3代相应财富见点佣金佣金提成:"+lookPointAward*map.get(user3.getRegisterLevel()));
					}
				}

				//获取四代
				if(user3!=null && user3.getRecommendUser()!=null){
					user4 = registerUserDAO.findUniqueBy("loginName",user3.getRecommendUser());
					if(user4!=null && "VIP4,VIP5,皇冠会员".indexOf(user4.getRegisterLevel())!=-1){
						Account ac = user4.getAccount();
						ac.setBalance(DoubleFormat.format(ac.getBalance()+lookPointAward*map.get(user4.getRegisterLevel())));
						accountDAO.merge(ac);
						transactionRecordDAO.save(new TransactionRecord(user4.getLoginName(), 
								loginName, "财富见点管理佣金", 
								lookPointAward*map.get(user4.getRegisterLevel()), 
								new Date(), 
								"财富见点管理佣金:激活会员编号为:"+loginName+"("+user.getRegisterLevel()+"),获得财富见点管理佣金:"+lookPointAward*map.get(user4.getRegisterLevel())));

//						System.out.println("见点管理佣金:会员编号为:"+loginName+"会员进行"+user.getRegisterLevel()+"激活，作为领导人("+user4.getRegisterLevel()+")将得到4代相应财富见点佣金佣金提成:"+lookPointAward*map.get(user4.getRegisterLevel()));
					}
				}
		
				//获取五代
				if(user4!=null && user4.getRecommendUser()!=null){
					user5 = registerUserDAO.findUniqueBy("loginName",user4.getRecommendUser());
					if(user5!=null && "VIP5,皇冠会员".indexOf(user5.getRegisterLevel())!=-1){
						Account ac = user5.getAccount();
						ac.setBalance(DoubleFormat.format(ac.getBalance()+lookPointAward*map.get(user5.getRegisterLevel())));
						accountDAO.merge(ac);
						transactionRecordDAO.save(new TransactionRecord(user5.getLoginName(), 
								loginName, "财富见点管理佣金", 
								lookPointAward*map.get(user5.getRegisterLevel()), 
								new Date(), 
								"财富见点管理佣金:激活会员编号为:"+loginName+"("+user.getRegisterLevel()+"),获得财富见点管理佣金:"+lookPointAward*map.get(user5.getRegisterLevel())));

//						System.out.println("见点管理佣金:会员编号为:"+loginName+"会员进行"+user.getRegisterLevel()+"激活，作为领导人("+user5.getRegisterLevel()+")将得到5代相应财富见点佣金佣金提成:"+lookPointAward*map.get(user5.getRegisterLevel()));
					}
				}
				//获取六代
				if(user5!=null && user5.getRecommendUser()!=null){
					user6 = registerUserDAO.findUniqueBy("loginName",user5.getRecommendUser());
					if(user6!=null && "皇冠会员".indexOf(user6.getRegisterLevel())!=-1){
						Account ac = user6.getAccount();
						ac.setBalance(DoubleFormat.format(ac.getBalance()+lookPointAward*map.get(user6.getRegisterLevel())));
						accountDAO.merge(ac);
						transactionRecordDAO.save(new TransactionRecord(user6.getLoginName(), 
								loginName, "财富见点管理佣金", 
								lookPointAward*map.get(user6.getRegisterLevel()), 
								new Date(), 
								"财富见点管理佣金:激活会员编号为:"+loginName+"("+user.getRegisterLevel()+"),获得财富见点管理佣金:"+lookPointAward*map.get(user6.getRegisterLevel())));

//						System.out.println("见点管理佣金:会员编号为:"+loginName+"会员进行"+user.getRegisterLevel()+"激活，作为领导人("+user5.getRegisterLevel()+")将得到5代相应财富见点佣金佣金提成:"+lookPointAward*map.get(user5.getRegisterLevel()));
					}
				}
			}
			
		}
					
	}
	/**
	 * 每天12点发放财富见点拥佣金
	 */
	public void gantLookPointAward(){
		
		System.out.println("------------发放财富见点佣金开始(有日封顶哦 )---------------------");
		TransactionRecordDTO dto = new TransactionRecordDTO();
		dto.setTransactionTypes(new String[]{"财富见点佣金"});
		dto.setOptDate(new Date());
		List<SingleGroupReportStatDTO> lists = transactionRecordDAO.transacGroupReportStatByLoginName(dto);
		for(SingleGroupReportStatDTO sdto : lists ){
			RegisterUser user = registerUserDAO.findUniqueBy("loginName", sdto.getGroupField());
			System.out.println("每天的财富见点佣金发放,会员:"+sdto.getGroupField()+",总佣金:"+sdto.getAggField()+
					",封顶是:"+InvestmentSum.level.get(user.getRegisterLevel())*10);
			Account ac = user.getAccount();
			if(InvestmentSum.level.get(user.getRegisterLevel())*10<DoubleFormat.format(sdto.getAggField())){
				ac.setBalance(DoubleFormat.format(ac.getBalance()+InvestmentSum.level.get(user.getRegisterLevel())*10));
				transactionRecordDAO.save(new TransactionRecord("system", 
						user.getLoginName(), "每天的财富见点佣金发放", 
						DoubleFormat.format(InvestmentSum.level.get(user.getRegisterLevel())*10*1.0), 
						new Date(), 
						"每天的财富见点佣金发放:"+DoubleFormat.format(InvestmentSum.level.get(user.getRegisterLevel())*10*1.0)));

			}else{
				ac.setBalance(DoubleFormat.format(ac.getBalance()+sdto.getAggField()));
				transactionRecordDAO.save(new TransactionRecord("system", 
						user.getLoginName(), "每天的财富见点佣金发放", 
						DoubleFormat.format(sdto.getAggField()), 
						new Date(), 
						"每天的财富见点佣金发放:"+DoubleFormat.format(sdto.getAggField())));


			}
			
			
		}
		System.out.println("------------发放财富见点佣金结束---------------------");
		
		TransactionRecordDTO dto1 = new TransactionRecordDTO();
		dto1.setTransactionTypes(new String[]{"财富见点管理佣金"});
		dto1.setOptDate(new Date());
		List<SingleGroupReportStatDTO> lists1 = transactionRecordDAO.transacGroupReportStatByLoginName(dto1);
		for(SingleGroupReportStatDTO sdto : lists1 ){
			RegisterUser user = registerUserDAO.findUniqueBy("loginName", sdto.getGroupField());
			System.out.println("每天的财富见点管理佣金发放,会员:"+sdto.getGroupField()+",总佣金:"+sdto.getAggField());
			Account ac = user.getAccount();
			ac.setBalance(DoubleFormat.format(ac.getBalance()+sdto.getAggField()));
			
			ac.setBalance(DoubleFormat.format(ac.getBalance()+sdto.getAggField()));
			transactionRecordDAO.save(new TransactionRecord("system", 
					user.getLoginName(), "每天的财富见点管理佣金发放", 
					DoubleFormat.format(sdto.getAggField()), 
					new Date(), 
					"每天的财富见点管理佣金发放:"+DoubleFormat.format(sdto.getAggField())));
			
		}
		
	}
	
	/**
	 * 成员倒钩佣金
	 * @param loginName
	 * @param sum
	 * @param type
	 */
	@Transactional
	private void daoGuaAward(String loginName,Double sum,String type,Date acTime){
		List<RegisterUser> rus = registerUserDAO.lastActiveUser(acTime);
		for(RegisterUser ru : rus){
			Account ac = ru.getAccount();
			ac.setBalance(DoubleFormat.format(ac.getBalance()+sum*0.05));
			accountDAO.merge(ac);
			transactionRecordDAO.save(new TransactionRecord(ru.getLoginName(), 
					loginName, "成员倒钩佣金", 
					DoubleFormat.format(sum*0.05), 
					new Date(), 
					"成员倒钩佣金("+type+"):激活会员编号为:"+loginName+"，获取成员倒钩佣金:"+DoubleFormat.format(sum*0.05)));

		}
	}
	
	
	//激活
	@Transactional
	public String accountActivate(String loginName){
		//得到当前用户
		RegisterUser regUser = registerUserDAO.findUniqueBy("loginName",loginName);
		regUser.setActivationTime(new Date());
		//当前用户帐户
		Account account = regUser.getAccount();
		
		//根据用户投资级别获取级别信息
//		InvestmentLevel il = investmentLevelDAO.findUniqueBy("levelName", regUser.getRegisterLevel());
		String registerLevel = regUser.getRegisterLevel();
		//得到推荐人账号
		RegisterUser recommendUser = registerUserDAO.findUniqueBy("loginName",regUser.getRecommendUser());
		Account recommendUserAccount = null;
		if(recommendUser!=null)
			recommendUserAccount = recommendUser.getAccount();
		
		//运营中心
		RegisterUser declarationCenterUser = registerUserDAO.findUniqueBy("loginName",regUser.getDeclarationCenters());
		Account declarationCenterAccount = declarationCenterUser.getAccount();
		//判断用户账号金额是否足够激活
		if(declarationCenterAccount.getBalance()>=InvestmentSum.level.get(registerLevel)){
			account.setStatus("Activation");
//			//70%进入购股钱包
			account.setPurchaseShareWallet(DoubleFormat.format(InvestmentSum.level.get(registerLevel)*0.7));
			transactionRecordDAO.save(new TransactionRecord(regUser.getLoginName(), 
					regUser.getLoginName(), "会员激活购股比例转入购股钱包", 
					DoubleFormat.format(InvestmentSum.level.get(registerLevel)*0.7), 
					new Date(), 
					"会员激活购股比例转入购股钱包:激活会员"+regUser.getLoginName()+"("+registerLevel+"):"+registerLevel));
			
			transactionRecordDAO.save(new TransactionRecord(regUser.getLoginName(), 
					regUser.getLoginName(), "会员激活", 
					-DoubleFormat.format(InvestmentSum.level.get(registerLevel)*0.3),
					new Date(), 
					"会员激活:激活会员"+regUser.getLoginName()+"("+registerLevel+")"));
			
			//提现钱包(扣除运营中心的)
			declarationCenterAccount.setBalance(DoubleFormat.format(declarationCenterAccount.getBalance()-InvestmentSum.level.get(registerLevel)));
			transactionRecordDAO.save(new TransactionRecord(declarationCenterUser.getLoginName(), 
					regUser.getLoginName(),
					"运营中心激活会员", 
					-DoubleFormat.format(InvestmentSum.level.get(registerLevel)*1.0), 
					new Date(),
					"运营中心激活会员:"+regUser.getLoginName()+"("+registerLevel+")"));
//					System.out.println("激活从提现钱包中扣取投资资金,投资级别:"+registerLevel+",投资金额:"+InvestmentSum.level.get(registerLevel));
			if(recommendUserAccount!=null){
				//1.销售佣金：20%(动态分配*20%,进入到推荐人提现钱包)
				System.out.println("销售佣金,余额:"+recommendUserAccount.getBalance()+",佣金:"+InvestmentSum.dynamic.get(registerLevel)*0.2);
				recommendUserAccount.setBalance(DoubleFormat.format(recommendUserAccount.getBalance()+InvestmentSum.dynamic.get(registerLevel)*0.2));
				transactionRecordDAO.save(new TransactionRecord(recommendUser.getLoginName(), 
						regUser.getLoginName(), "销售佣金", 
						DoubleFormat.format(InvestmentSum.dynamic.get(registerLevel)*0.2), 
						new Date(), 
						"销售佣金:激活会员"+regUser.getLoginName()+"("+regUser.getRegisterLevel()+"),获得销售佣金:"+DoubleFormat.format(InvestmentSum.dynamic.get(registerLevel)*0.2)));
				
				//销售佣金倒勾奖
//				System.out.println("这里的时间是:"+recommendUser.getLoginName()+"+++"+recommendUser.getActivationTime());
				daoGuaAward(loginName,DoubleFormat.format(InvestmentSum.dynamic.get(registerLevel)*0.2),"销售佣金",recommendUser.getActivationTime());
			}
			//财富见点佣金
			lookPointAward(loginName);
			
			
//			2.销售管理佣金：拥有销售奖1—6代的管理奖
			leaderManagementAward(DoubleFormat.format(InvestmentSum.dynamic.get(registerLevel)*0.2),loginName);
			
			//3.运营中心
			//得到报单人
			if(declarationCenterUser!=null){
				System.out.println("运营中心,余额:"+declarationCenterAccount.getBalance()+",佣金:"+InvestmentSum.dynamic.get(regUser.getRegisterLevel())*0.05);
				declarationCenterAccount.setBalance(DoubleFormat.format(declarationCenterAccount.getBalance()+InvestmentSum.dynamic.get(regUser.getRegisterLevel())*0.05));
				transactionRecordDAO.save(new TransactionRecord(declarationCenterUser.getLoginName(), 
						regUser.getLoginName(), "运营中心", 
						DoubleFormat.format(InvestmentSum.dynamic.get(regUser.getRegisterLevel())*0.05), 
						new Date(), 
						"运营中心:激活会员"+regUser.getLoginName()+"("+regUser.getRegisterLevel()+"),获得运营中心:"+DoubleFormat.format(InvestmentSum.dynamic.get(regUser.getRegisterLevel())*0.05)));
			}
			
			accountDAO.merge(account);

			regUser.setStatus("Activation");
			
			
			registerUserDAO.merge(regUser);
			
			return "success";
			
//			//自动将购股钱包进行购股
//			return sellService.buyShare(loginName, account.getPurchaseShareWallet());
			
		}else{
			return "Failure";
		}
		
	}
	
	/**
	 * 查询当前用户财务信息
	 * @return
	 */
	@Transactional
	public AccountDTO findAccountInfo(){
		AccountDTO acDTO = new AccountDTO();
		HttpSession session = ServletActionContext.getRequest().getSession();
		if(session.getAttribute("loginName")!=null){
			RegisterUser regUser = registerUserDAO.findUniqueBy("loginName", session.getAttribute("loginName"));
			Account ac = regUser.getAccount();
			acDTO.entity2dto(ac,acDTO);
		}
		return acDTO;
	}
	/**
	 * 根据当前登录用户获取账号
	 * @return
	 */
	@Transactional
	public Account findAccountByLoginName(){
		Account ac = new Account();
		HttpSession session = ServletActionContext.getRequest().getSession();
		if(session.getAttribute("loginName")!=null){
			RegisterUser regUser = registerUserDAO.findUniqueBy("loginName", session.getAttribute("loginName"));
			ac = regUser.getAccount();
			
		}else{
			ac = null;
		}
		return ac;
	}
	/**
	 * 根据当前登录用户获取账号
	 * @param loginName
	 * @return
	 */
	@Transactional
	public Account findAccountByLoginName(String loginName){
		RegisterUser regUser = registerUserDAO.findUniqueBy("loginName", loginName);
		Account ac = regUser.getAccount();
		return ac;
	};
	
	/**
	 * 根据当前登录用户获取账号
	 * @param loginName
	 * @return
	 */
	@Transactional
	public AccountDTO findAccountInfoByLoginName(String loginName){
		AccountDTO dto = new AccountDTO();
		RegisterUser regUser = registerUserDAO.findUniqueBy("loginName", loginName);
		Account ac = regUser.getAccount();
		dto.entity2dto(ac, dto);
		return dto;
	};
	/**
	 * 提现
	 * @param loginName
	 */
	@Transactional
	public String extract(String loginName,Double extractMoney){
		RegisterUser regUser = registerUserDAO.findUniqueBy("loginName", loginName);
		Account ac = regUser.getAccount();
		if(extractMoney>=1 && ac.getBalance()>=extractMoney && "Activation".equals(ac.getStatus())){
			ac.setBalance(DoubleFormat.format(ac.getBalance()+extractMoney));
			ac.setPercentageSeventy(DoubleFormat.format(ac.getPercentageSeventy()-extractMoney));
			accountDAO.merge(ac);
			
			//保存历史记录 
			TransactionRecord tr = new TransactionRecord();
			tr.setLoginName(loginName);
			tr.setOptDate(new Date());
			tr.setSumOfMoney(extractMoney);
			tr.setTransactionType(TranType.TiXian);
			tr.setRemark("提现");
			transactionRecordDAO.save(tr);
			
			return "Success";
		}else{
			return "Failure";
		}
		
	}
	/**
	 * 更新账号信息
	 * @param dto
	 */
	@Transactional
	public void updateAccount(AccountDTO dto){
		if(dto!=null){
			Account ac = accountDAO.findById(dto.getAccountId());
			ac.setBalance(dto.getBalance());
			ac.setHaveShare(dto.getHaveShare());
			ac.setManualBuyQuota(dto.getManualBuyQuota());
			ac.setManualBuyQuotaTotal(dto.getManualBuyQuotaTotal());
			ac.setAutoBuyQuota(dto.getAutoBuyQuota());
			ac.setAutoBuyQuotaTotal(dto.getAutoBuyQuotaTotal());
			ac.setPercentageSeventy(dto.getPercentageSeventy());
			ac.setPercentageThirty(dto.getPercentageThirty());
			
			ac.setAccountWallet(dto.getAccountWallet());
			ac.setAutoUpgradeWallet(dto.getAutoUpgradeWallet());
			ac.setPurchaseShareWallet(dto.getPurchaseShareWallet());
			
			accountDAO.merge(ac);
		}
		
	}
	/**
	 * 追加资金
	 * @param loginName
	 * @param value
	 */
	public String addTo(String loginName,Double value){
		
		RegisterUser regUser = registerUserDAO.findUniqueBy("loginName", loginName);
		Account ac = regUser.getAccount();
		
		//判断追加金额是否已超过
		if(value<=ac.getAddTo()){
			ac.setBalance(DoubleFormat.format(ac.getBalance()+value));
			ac.setAddTo(ac.getAddTo()-value);
			accountDAO.merge(ac);
			
			TransactionRecord tr = new TransactionRecord();
			tr.setTransactionType("addTo");
			tr.setLoginName(loginName);
			tr.setOptDate(new Date());
			tr.setSumOfMoney(value);
			tr.setRemark("追加资金");
			transactionRecordDAO.save(tr);
			
			return "Success";
		}else{
			return "Failure";
		}
	}
	
}
